from httpUtil import HttpUtil
from thing_alink_car001 import CustomerThingCar001
from thing_alink_car002 import CustomerThingCar002
from runTimeLogUiUtil import *
from threadUtil import *

http = HttpUtil('http://192.168.31.8:8080/robot/')
car001 = CustomerThingCar001()
car002 = CustomerThingCar002()
thread = ThreadUtil()


class Main():
    def login(self):
        """
        获取tokenId
        :return:
        """
        data = {
            "userName": 'admin',
            "password": 'cqcee18'
        }
        self.log.runFileLog('发起登录')
        res = http.post('loginVerify', data)
        if res != '':
            res = eval(res)
        else:
            self.log.exceptFileLog('登录失败，程序即将退出')
            sys.exit(0)
        self.log.tempFileLog(f'登录返回数据{res}')
        self.tokenId = res['data']['tokenId']
        self.log.runFileLog(f'登录成功，获取tokenId={self.tokenId}')

    def getRunningCarsForMap(self):
        headers = {'Authorization': self.tokenId}
        res = http.post('api/currentCar/runningCarsForMap', {}, 3, headers)
        if res == '':
            self.log.exceptFileLog('获取运行车辆数据失败，请检查网络设置！')
        else:
            res = eval(res)
            self.log.tempFileLog(f'获取运行车辆返回数据{res}')
            if res['error']['returnCode'] != 0:
                self.log.tempFileLog('token过期')
                self.login()
                return self.getRunningCarsForMap()
            else:
                runningCarsForMap = res['data']['list']
                self.log.runFileLog(f'获取运行车辆数据成功，获取runningCarsForMap={runningCarsForMap}，当前在线车辆数={len(runningCarsForMap)}')
                return runningCarsForMap

    def getCarPower(self, carId):
        data = {
            'carId': carId
        }
        headers = {'Authorization': self.tokenId}
        res = http.post('api/currentCar/carPower', data, 3, headers)
        if res == '':
            self.log.exceptFileLog(f'获取车辆{carId}电量失败，请检查网络设置！')
        else:
            res = eval(res)
            self.log.tempFileLog(f'获取车辆{carId}电量返回数据{res}')
            if res['error']['returnCode'] != 0:
                self.log.tempFileLog('token过期')
                self.login()
                return self.getCarPower(carId)
            else:
                power = res['data']
                self.log.runFileLog(f'获取车辆{carId}电量数据成功，获取power={power}')
                return power

    def getCarMileage(self, carId):
        data = {
            'carId': carId
        }
        headers = {'Authorization': self.tokenId}
        res = http.post('api/currentCar/singleCarTotalMileage', data, 3, headers)
        if res == '':
            self.log.exceptFileLog(f'获取车辆{carId}里程失败，请检查网络设置！')
        else:
            res = eval(res)
            self.log.tempFileLog(f'获取车辆{carId}里程返回数据{res}')
            if res['error']['returnCode'] != 0:
                self.log.tempFileLog('token过期')
                self.login()
                return self.getCarMileage(carId)
            else:
                mileage = res['data']
                self.log.runFileLog(f'获取车辆{carId}里程数据成功，获取power={mileage}')
                return mileage

    def getCarRunHour(self, carId):
        data = {
            'carId': carId
        }
        headers = {'Authorization': self.tokenId}
        res = http.post('api/currentCar/singleCarTotalRunHour', data, 3, headers)
        if res == '':
            return self.log.exceptFileLog(f'获取车辆{carId}运行时间失败，请检查网络设置！')
        else:
            res = eval(res)
            self.log.tempFileLog(f'获取车辆{carId}运行时间返回数据{res}')
            if res['error']['returnCode'] != 0:
                self.log.tempFileLog('token过期')
                self.login()
                return self.getCarRunHour(carId)
            else:
                runHour = res['data']
                self.log.runFileLog(f'获取车辆{carId}运行时间数据成功，获取power={runHour}')
                return runHour

    def connectAliyun(self):
        self.log.runFileLog('发起阿里云异步连接请求')
        car001.connect_async()
        car002.connect_async()

    def sendAliyun(self, runningCarsForMap):
        # if (len(runningCarsForMap) == 2):
        for item in runningCarsForMap:
            if (item['carName'] == '1号'):
                GPS_info = item['GPS_info']
                data = self.fInterpreter(GPS_info, 'robot1')
                self.log.runFileLog(f'向阿里云上传车辆robot1历史数据{data}')
                car001.user_loop('2', data)
            elif (item['carName'] == '2号'):
                GPS_info = item['GPS_info']
                data = self.fInterpreter(GPS_info, 'robot2')
                self.log.runFileLog(f'向阿里云上传车辆robot2历史数据{data}')
                car002.user_loop('2', data)
        # elif (len(runningCarsForMap) == 1):
        #     item = runningCarsForMap[0]
        #     if (item['carName'] == '1号'):
        #         GPS_info = item['GPS_info']
        #         data = self.fInterpreter(GPS_info, 'robot1')
        #         car001.user_loop('2', data)
        #
        #         data2 = {
        #             "Mileage": self.getCarMileage('robot2'),
        #             "RunTime": self.getCarRunHour('robot2'),
        #             # "Battery": self.getCarPower('robot2')
        #         }
        #         car002.user_loop('2', data2)
        #     elif (item['carName'] == '2号'):
        #         GPS_info = item['GPS_info']
        #         data = self.fInterpreter(GPS_info, 'robot2')
        #         car002.user_loop('2', data)
        #
        #         data1 = {
        #             "Mileage": self.getCarMileage('robot1'),
        #             "RunTime": self.getCarRunHour('robot1'),
        #             # "Battery": self.getCarPower('robot1')
        #         }
        #         car001.user_loop('2', data1)
        # elif (len(runningCarsForMap) == 0):
        #     data1 = {
        #         "Mileage": self.getCarMileage('robot1'),
        #         "RunTime": self.getCarRunHour('robot1'),
        #         # "Battery": self.getCarPower('robot1')
        #     }
        #     data2 = {
        #         "Mileage": self.getCarMileage('robot2'),
        #         "RunTime": self.getCarRunHour('robot2'),
        #         # "Battery": self.getCarPower('robot2')
        #     }
        #     car001.user_loop('2', data1)
        #     car002.user_loop('2', data2)

    def fInterpreter(self, GPS_info, carId):
        data = {
            "Mileage": self.getCarMileage(carId),
            "RunTime": self.getCarRunHour(carId),
            "Battery": self.getCarPower(carId),
            "X": GPS_info['x'],
            "Y": GPS_info['y'],
            "Heading": int(GPS_info['cheading'])
        }
        return data

    def setup(self):
        self.login()
        self.connectAliyun()
        while True:
            runningCarsForMap = self.getRunningCarsForMap()
            self.sendAliyun(runningCarsForMap)
            time.sleep(1)


if __name__ == '__main__':
    main = Main()
    app = QtWidgets.QApplication(sys.argv)
    log = RunTimeLogUiUtil()
    _translate = QtCore.QCoreApplication.translate
    log.Form.setWindowTitle(_translate("Form", "无人车数据中转日志"))
    main.log = log
    thread.startThread(main.setup)
    sys.exit(app.exec_())
